/* Laboratorio # 2 - Administración de bases de datos
 Jorge Fallas Ramos         402090469
 José Roberto Sánchez       115400070
 Daniel Villalobos Venegas  402110100
 */
package monitorinitdb.Vista;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import monitorinitdb.ConectorOracle;
import monitorinitdb.ConectorUnix;
import monitorinitdb.ConectorWindows;

public class Ventana extends JFrame implements ActionListener {

    ArrayList<JTextField> campos;
    String[] acciones = {"Conectar", "Limpiar", "Salir"};
    static Ventana v;
    JPasswordField pass;

    public static Ventana getInstance() {
        if (v == null) {
            v = new Ventana();
        }
        return v;
    }

    private Ventana() throws HeadlessException {
        configInicial();
        configMenu();
        configComponentes();
        setTitle("ORACLE Init DataBase... Inicio");
    }

    private void configComponentes() {
        Dimension dimP = new Dimension(150, 30);
        campos = new ArrayList<>();
        setLayout(new BorderLayout());

        JPanel f = new JPanel(new BorderLayout());
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.add(Box.createRigidArea(new Dimension(30, 40)));
        p.add(Box.createHorizontalGlue());
        p.add(barraUser(dimP));
        p.add(Box.createHorizontalGlue());
        p.add(barraContrasena(dimP));
        p.add(Box.createHorizontalGlue());

        f.add(p, BorderLayout.CENTER);
        f.add(new JLabel(new ImageIcon(getClass().getResource("/monitorinitdb/Vista/Imagenes/imaInicio2.png"))), BorderLayout.NORTH);
        f.add(botonesFinal(dimP), BorderLayout.SOUTH);
        add(f, BorderLayout.CENTER);
    }

    private void configMenu() {
        JMenuBar barra = new JMenuBar();
        setJMenuBar(barra);
        JMenu m = new JMenu("General");
        barra.add(m);
        JMenuItem item;
        for (String s : acciones) {
            item = new JMenuItem(s);
            m.add(item);
            item.addActionListener(this);
        }
    }

    private JPanel botonesFinal(Dimension dim) {
        JPanel l = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton b;
        for (String s : acciones) {
            b = new JButton(s);
            b.addActionListener(this);
            l.add(b);
        }
        return l;
    }

    private JPanel barraContrasena(Dimension dim) {
        JPanel l = new JPanel(new GridLayout(1, 2));
        l.add(new JLabel("Contraseña:"));
        pass = new JPasswordField();
        pass.setName("Contraseña");
        pass.setPreferredSize(dim);
        l.add(pass);
        return l;
    }

    private JPanel barraUser(Dimension dimP) {
        JPanel l = new JPanel(new GridLayout(1, 2));
        l.add(new JLabel("Usuario:"));
        l.add(genTextF(dimP, "Usuario"));
        return l;
    }

    private JTextField genTextF(Dimension dimP, String nombre) {
        JTextField c = new JTextField();
        c.setName(nombre);
        c.setPreferredSize(dimP);
        campos.add(c);
        return c;
    }

    /*private JPanel campRol(Dimension dimP) {
     JPanel l = new JPanel(new GridLayout(1, 2));
     l.add(new JLabel("Rol:"));
     l.add(genTextF(dimP, "Rol"));
     return l;
     }*/

    /*private JPanel barraServ(Dimension dimP) {
     JPanel l = new JPanel(new GridLayout(1, 4));
     l.add(new JLabel("Servidor:"));
     l.add(genTextF(dimP, "Servidor"));
     l.add(new JLabel("Puerto:"));
     l.add(genTextF(dimP, "Puerto"));
     return l;
     }*/

    /*private JPanel barra2(Dimension dimP) {
     JPanel l = new JPanel(new GridLayout(1, 2));
     l.add(new JLabel("SID:"));
     l.add(genTextF(dimP, "SID"));
     return l;
     }*/
    private void configInicial() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 380));
        setResizable(false);
    }

    private void Conectar() throws Exception {
        for (JTextField j : campos) {
            if (j.getText().equals("")) {
                throw new Exception("Falta por llenar el campo " + j.getName());
            }
        }
        String passwd = String.valueOf(pass.getPassword());
        if (passwd.equals("")) {
            throw new Exception("Falta por llenar el campo " + pass.getName());
        }
        System.out.println("Conectando a la base de datos");
        String os = System.getProperty("os.name").toLowerCase();
        String user = campos.get(0).getText();
        if (os.equals("linux")) {
            System.out.println("Conectando Linux");
            ConectorOracle con_unix = new ConectorUnix(user, passwd);
            VentConfig.getInstance().mostrar();
            VentConfig.setConexion(con_unix);
            setVisible(false);
        } else if (os.equals("windows 7")) {
            System.out.println("Conectando Windows");
            ConectorOracle con_windows = new ConectorWindows(user, passwd);
            VentConfig.getInstance().mostrar();
            VentConfig.setConexion(con_windows);
            setVisible(false);
        } else {
            throw new Exception("Sistema operativo " + os + " no soportado\nEspere a la siguiente versión de la aplicación");
        }
    }

    public void mostrar() {
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        Ventana.getInstance().mostrar();
    }

    void limpiar() {
        for (JTextField t : campos) {
            t.setText("");
        }
        pass.setText("");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        switch (e.getActionCommand()) {
            case "Salir": {
                System.exit(0);
            }
            break;
            case "Limpiar": {
                limpiar();
            }
            break;
            case "Conectar": {
                try {
                    Conectar();
                } catch (Exception ex) {
                    if (!(ex instanceof NullPointerException)) {
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.WARNING_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(null, "Error de capa 8", "Error", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }
            break;
            default:
                throw new UnsupportedOperationException("Accion " + e.getActionCommand() + " no implementado");
        }
    }
}
